package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    final private String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 用户登录
     * @param loginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO loginDTO){
        // 1 调用微信接口  获取当前用户openId
        String openid = getOpenId(loginDTO.getCode());

        //  2 判断openId 是否为空 若为空 抛出业务异常
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 获取当前用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenid, openid);

        User user  = super.getOne(queryWrapper);
        if (user == null){
            // 当前用户为新用户
            user = User.builder().
                    openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            super.save(user);
        }
        // 返回用户对象
        return user;
    }

    /**
     * 获取openId
     * @param code
     * @return
     */
    public String getOpenId(String code){
        // 1 1 参数构建
        Map<String, String> claims =  new HashMap<>();
        claims.put("appid", weChatProperties.getAppid());  // appid
        claims.put("secret", weChatProperties.getSecret()); // secret
        claims.put("js_code", code); // js_code
        claims.put("grant_type","authorization_code"); // grant_type
        // 1 2 发送请求
        String jsonStr  = HttpClientUtil.doGet(WX_LOGIN_URL, claims);
        // 2 3 响应数据  获取token
        JSONObject jsObject = JSON.parseObject(jsonStr);
        String openid = jsObject.getString("openid");
        log.info("微信返回信息:{}", openid);
        return openid;
    }
}
